<?php

class indexControl extends commonControl {

    //版权信息|1
    function index() {
        $_SESSION['step'] = 1;
        $this->display();
    }

    //检测环境|2
    function check() {
        if ($_SESSION['step'] < 1) {
            go("index");
        }
        $_SESSION['step'] = 2;
        $uploadsize = ini_get("upload_max_filesize"); //允许上传的单个文件最大值
        $gd = gd_info(); //获得GD库所有信息
        $gdversion = $gd['GD Version']; //获得GD库版本
        $diskspace = get_size(disk_free_space('.'));
        $system = array(
            "phpversion" => PHP_VERSION,
            "phpos" => PHP_OS,
            "uploadsize" => $uploadsize,
            "gdversion" => $gdversion,
            "diskspace" => $diskspace
        );
        $this->assign("system", $system);
        $this->display();
    }

    //配置数据库连接|3
    function setconfig() {
        if ($_SESSION['step'] < 2) {
            go("check");
        }
        $_SESSION['step'] = 3;
        $this->display();
    }

    //安装数据库|4
    function installdb() {
        // p($_POST);die;
        
        if ($_SESSION['step'] < 3) {
            go("setconfig");
        }
        $_SESSION['adminpost'] = $_POST['admin'];
        $_SESSION['step'] = 4;
        $this->writeconfig();
        $this->display();
    }

    //写入数据库配置
    function writeconfig() {
        //  $link = @mysql_connect($_POST['DB_HOST'] . ":" . $_POST['DB_PORT'], $_POST['DB_USER'], $_POST['DB_PASSWORD']);
        // $select_db = @mysql_select_db($_POST['DB_DATABASE']);
        // if (!$link || !$select_db) {
        //     $this->error("数据库配置错误");
        // }
        $str = "<?php \n";
        $str.='if (!defined("PATH_HD")) exit("No direct script access allowed");';
        $str.="\n return " . var_export($_POST['db'], true) . "\n?>";
        if (!@file_put_contents("../config/db.php", $str)) {
            $this->error("config目录不可写，请修改权限");
        }
    }

    //写入数据库
    function createtable() {
        if ($_SESSION['step'] < 3) {
            go("setconifg");
        }
        $_SESSION['step'] = 4;
        $dbconfig = include "../config/db.php";
        $dbprefix = $dbconfig['DB_PREFIX']; //表前缀
        $sql = file_get_contents(PATH_APP . '/data/hdinfo.sql');
        $sql = explode(';',file_get_contents(PATH_APP . '/data/hdinfo.sql'));
        //连接数据库
        $db = mysql_connect($dbconfig['DB_HOST'], $dbconfig['DB_USER'], $dbconfig['DB_PASSWORD']);
        mysql_query("SET NAMES UTF8");
        mysql_query("CREATE DATABASE " . $dbconfig['DB_DATABASE'] . " CHARSET utf8");
        mysql_query("USE " . $dbconfig['DB_DATABASE']);
        if (!$db) {
            $this->error("数据库连接配置错误");
        }
        $buffer = ini_get("output_buffering");
        foreach ($sql as $v) {
            if (empty($v)) {
                continue;
            }
            echo str_repeat(" ", $buffer); //将缓冲区填满
            if (preg_match("/CREATE\s+TABLE\s+IF\s+NOT\s+EXISTS\s+`(.*?`)/iU" , $v, $tb)) {
                $t = str_replace('CREATE TABLE IF NOT EXISTS `' . $tb[1], 'CREATE TABLE IF NOT EXISTS `' . $dbprefix . $tb[1], $v);
                 sleep(1);
                if (mysql_query($t)) {
                    echo "<span style='font-size:14px;height:20px;display:block;width:500px;'>创建数据表" . $dbprefix . $tb[1] . "<span style='color:green'>成功</span></span>";
                    echo "<script>document.body.scrollTop = document.body.scrollHeight;</script>";
                } else {
                    echo "<span style='font-size:14px;height:20px;display:block;width:500px;color:#f00;'>创建数据表" . $dbprefix . $tb[1] . "失败...</span>";
                    echo "<script>document.body.scrollTop = document.body.scrollHeight;</script>";
                }
            }
            if (preg_match("/DELETE\s+FROM\s+`(.*?`)/iU" , $v , $tb)) {
                $t = str_replace('DELETE FROM `' . $tb[1], 'DELETE FROM `' . $dbprefix . $tb[1], $v);
                mysql_query($t);
            }
            if (preg_match("/INSERT\s+INTO\s+`([^\(]*?`)/iU" , $v , $tb)) {
                $t = str_replace('INSERT INTO `' . $tb[1], 'INSERT INTO `' . $dbprefix . $tb[1], $v);
                if (!mysql_query($t)) {
                    echo "<span style='font-size:14px;height:20px;display:block;width:500px;color:#f00;'>添加" . $dbprefix . $tb[1] . "系统数据失败...</span>";
                }
            }

            ob_flush();
            flush();

        }
        //写入管理员帐号
        $admin = $_SESSION['adminpost'];
        $username = $admin['username'];
        $_SESSION['easyuser'] = $admin['username'];
        $password = serialize($admin['password']);
        $email = $admin['email'];
        $registime = $logintime = $_SERVER['REQUEST_TIME'];
        $regisip = $loginip = $_SERVER['REMOTE_ADDR'];
        $sql = 'INSERT INTO `' . $dbprefix . 'user` (`username`,`password`,`email`,`logintime`,`loginip`,`registime`,`regisip`) VALUES("' . $username . '","' . $password . '","' . $email . '","' . $logintime . '","' . $loginip . '","' . $registime . '","' . $regisip . '")';
        mysql_query($sql);
        $insertId = mysql_insert_id();
        mysql_query('INSERT INTO `' . $dbprefix . 'user_role` (`uid` , `rid`) VALUES (' . $insertId . ',1)');
        mysql_query('INSERT INTO `' . $dbprefix . 'userinfo` (`uid`) VALUES(' . $insertId . ')');
        echo "<script>
            setTimeout(function(){
                parent.window.location.href='" . __CONTROL__ . "/finish';
            },0)
            </script>";
        exit;
    }

    //安装完成
    function finish() {
        if ($_SESSION['step'] < 4) {
            go("index");
        }
        unset($_SESSION['step']); //卸载安装步骤
        file_put_contents(PATH_APP . "/lock.php", "");
        
        $webUrl = str_replace('/install', '', __WEB__);
        $adminUrl = $webUrl . '/admin';
        $this->assign('webUrl',$webUrl);
        $this->assign('adminUrl',$adminUrl);
        $this->display();
    }

}